//
//  testwebViewController.m
//  navigation
//
//  Created by user on 16/7/14.
//  Copyright © 2016年 Facebook. All rights reserved.
//

#import "testwebViewController.h"
#import "MBProgressHUD.h"

@interface testwebViewController ()
@property (weak, nonatomic) IBOutlet UITextField *urltext;
@property (weak, nonatomic) IBOutlet UITextField *duankoutext;
@property (weak, nonatomic) IBOutlet UIWebView *myweb;
@property (weak, nonatomic) IBOutlet UITableView *table;

@end

@implementation testwebViewController{
  bool righ;
  NSMutableArray *urlarr;
}

- (IBAction)hidec:(id)sender {
    self.table.hidden=!self.table.hidden;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    urlarr=[NSMutableArray array];
  if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
  }
  if (self.jsurl.length) {
    self.urltext.text=self.jsurl;
    [self inclick:nil];
  }
  if(self.AutochangeMoudle){
    MBProgressHUD *  mb = [MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    mb.mode = MBProgressHUDModeIndeterminate;
  }

}
- (IBAction)inclick:(id)sender {
    NSURL *url=[NSURL URLWithString:self.urltext.text ];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [self.myweb loadRequest:request];
}
- (IBAction)bianliclick:(id)sender {
NSString *duan=@"";
    if (self.duankoutext.text.length>0) {
        duan=[NSString stringWithFormat:@":%@",self.duankoutext.text];
    }
    NSString *str0=@"http://192.168.1.";
    NSString *str=@"";
      MBProgressHUD *  mb = [MBProgressHUD showHUDAddedTo:self.view  animated:YES];
  mb.mode = MBProgressHUDModeIndeterminate;
      [mb hide:YES afterDelay:255*0.1+1];
    for (int i=1; i<256; i++) {


        str=[NSString stringWithFormat:@"%@%D%@",str0,i,duan];
        NSURL *url=[NSURL URLWithString:str ];
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
        request.timeoutInterval=5.0;//设置请求超时为5秒
        request.HTTPMethod=@"GET";//设置请求方法
        request.cachePolicy=NSURLRequestReloadIgnoringCacheData;
        double delayInSeconds = 0.1*i;
        __block testwebViewController* bself = self;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

            NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

            ; });
        
        //        NSError *err = nil;
        
        //        righ=  [url checkResourceIsReachableAndReturnError:&err];
      

        
    }

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return urlarr.count;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"aa"];
  if (cell == nil){
    cell = [[UITableViewCell alloc]
            initWithStyle:UITableViewCellStyleDefault
            reuseIdentifier:@"aa"];
    
  }
  cell.textLabel.minimumScaleFactor=0.2;
  cell.textLabel.adjustsFontSizeToFitWidth=YES;
  cell.textLabel.text=urlarr[indexPath.row];
  return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
  UIPasteboard *pab = [UIPasteboard generalPasteboard];
  [pab setString:urlarr[indexPath.row]];
  NSURL *url=[NSURL URLWithString:urlarr[indexPath.row] ];
  NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
  [self.myweb loadRequest:request];
  
  
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
  
  MBProgressHUD *  mb = [MBProgressHUD showHUDAddedTo:self.myweb  animated:YES];
  mb.mode = MBProgressHUDModeIndeterminate;

  
    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"%@",requestString);
    return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSURLRequest *request=webView.request;
    
    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    self.urltext.text=requestString;
    NSLog(@"----------%@",requestString);
  [MBProgressHUD hideAllHUDsForView:self.view  animated:YES];
  [MBProgressHUD hideAllHUDsForView:self.myweb  animated:YES];
  MBProgressHUD *  mb = [MBProgressHUD showHUDAddedTo:self.myweb  animated:YES];
  mb.labelText=@"success";
  mb.mode = MBProgressHUDModeText;
  [mb hide:mb afterDelay:0.5];
  NSLog(@"webdidfinish2");
  if (!self.AutochangeMoudle) {
    return;
  }
  NSLog(@"webdidfinish1");
  NSString *JsToGetHTMLSource = @"document.getElementsByTagName('html')[0].innerHTML";
  NSString *HTMLSource = [webView stringByEvaluatingJavaScriptFromString:JsToGetHTMLSource];
  
  NSString *str=[HTMLSource stringByReplacingOccurrencesOfString:@" " withString:@""];
  NSArray *array = [str componentsSeparatedByString:@"AppRegistry.registerComponent('"];
  if(array.count>=2){
    int i= MIN(100,[array[1] length]);
    NSString *sub = [array[1] substringToIndex:i];
      NSArray *array2 = [sub componentsSeparatedByString:@"'"];
    if (array2.count>=2){
      self.preVC.moduletext.text=array2[0];
      [self.navigationController popToRootViewControllerAnimated:YES];
    }
  }


//  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
//    
//    // 解析
////    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//
//  }];
//  NSLog(@"%@",HTMLSource);
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
  [MBProgressHUD hideAllHUDsForView:self.view  animated:YES];
  [MBProgressHUD hideAllHUDsForView:self.myweb  animated:YES];
  MBProgressHUD *  mb = [MBProgressHUD showHUDAddedTo:self.myweb  animated:YES];
  mb.labelText=error.domain;
  mb.mode = MBProgressHUDModeText;
  [mb hide:mb afterDelay:1.5];
    
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
    
    NSLog(@"11%@",[res allHeaderFields]);
    

    NSURL *url=connection.currentRequest.URL;
    NSString *stru=[NSString stringWithFormat:@"%@",url];
    [urlarr insertObject:stru atIndex:0];
    [self.table reloadData];
}

////接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //    [self.myResult appendData:data];
    
}

//数据传输完成之后执行方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{
//    NSString *receiveStr = [[NSString alloc]initWithData:self.myResult encoding:NSUTF8StringEncoding];
    
//    NSLog(@"22%@",receiveStr);
    
}

//网络请求时出现错误（断网，连接超时)执行方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{
    NSLog(@"33%@",[error localizedDescription]);
}


@end
